﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
using CharacterTrailLibrary.Exceptions;
using CharacterTrailLibrary.Factory;
using CharacterTrailLibrary.Interface;
using CharacterTrailLibrary.Persist.BLL.Model;
using CharacterTrailLibrary.Security;
using Telegnosis.Framework.Constants;

namespace CharacterTrailLibrary.Impl
{
    public class ExcelImportor:IExcelImportor 
    {
         public const string TableName = "BOM数据$";
         public DataTable GetDataTable(string fileName)
         {
             DataTable excelTable = null;
             var ds = new DataSet();

             var conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";" + "Extended Properties=Excel 8.0;");
             conn.Open();
             //var schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
             //string tableName = schemaTable.Rows[0][2].ToString().Trim();//获取 Excel 的表名，默认值是sheet1
             var strSql = "select * from [" + TableName + "]";
             var myData = new OleDbDataAdapter(strSql, conn);
             myData.Fill(ds, TableName);

             conn.Close();
      
             excelTable = ds.Tables[TableName];

             var dataRows = new List<DataRow>();

             foreach (DataRow row in excelTable.Rows)
             {
                 if(String.IsNullOrEmpty(row["产品代码"].ToString()))
                 {
                     dataRows.Add(row);
                 }
             }
             foreach (DataRow row in dataRows)
             {
                 excelTable.Rows.Remove(row);
             }
             excelTable.Columns.Add("ParentItemId", typeof (Int32));
             excelTable.Columns.Add("ChildItemId", typeof (Int32));
             excelTable.AcceptChanges();

             DataTable returnTable = excelTable.Clone();
             IStaticDataQuerier staticDataQuerier = InstanceFactory.GetStaticDataQuerier();
             foreach (DataRow row in excelTable.Rows)
             {
                 //从数据库中找产品/物料代码
                 var iCItemModelParent =  staticDataQuerier.GetVIcItemQueryModel(row["产品代码"].ToString().Trim());
                 if(iCItemModelParent == null)
                 {
                     throw new AppException(String.Format("产品/物料代码{0}在系统中没有维护！",row["产品代码"].ToString().Trim()));
                 }

                 var iCItemModelChild =  staticDataQuerier.GetVIcItemQueryModel(row["物料代码"].ToString().Trim());
                 if(iCItemModelChild == null)
                 {
                     throw new AppException(String.Format("产品/物料代码{0}在系统中没有维护！", row["物料代码"].ToString().Trim()));
                 }

                 DataRow dr = returnTable.NewRow();
                 dr.ItemArray = row.ItemArray;
                 dr["ParentItemId"] = iCItemModelParent.FItemId;
                 dr["ChildItemId"] = iCItemModelChild.FItemId;
                 returnTable.Rows.Add(row);
             }
             returnTable.AcceptChanges();
             return returnTable;
         }


         public void ImportToDb(DataTable dataTable)
         {
             var list = new List<TBomHeaderModel>();
             foreach (DataRow row in dataTable.Rows)
             {
                 var bomHeaderModel = new TBomHeaderModel();
                 bomHeaderModel.EditFlag = Enums.EditFlag.New;
                 bomHeaderModel.RowGuid = Guid.NewGuid().ToString("N");
                 bomHeaderModel.BomNumber = row[@"BOM代码"].ToString();
                 //ID为内码，应该和物料的内码一致，暂时不管。
                 //bomHeaderModel.ParentItemId = ？？？
                 bomHeaderModel.ParentItemNumber = row[@"产品代码"].ToString();

                 //如果产品代码不存在，则该行跳过
                 if (String.IsNullOrEmpty(bomHeaderModel.ParentItemNumber))
                 {
                     continue;
                 }

                 bomHeaderModel.ParentItemName = row[@"产品名称"].ToString();
                 //ID为内码，应该和物料的内码一致，暂时不管。
                 //bomHeaderModel.ChildItemId = ？？？
                 bomHeaderModel.ChildItemNumber = row[@"物料代码"].ToString();
                 bomHeaderModel.ChildItemName = row[@"物料名称"].ToString();

                 bomHeaderModel.ProcessNo = row[@"工序号"].ToString();
                 bomHeaderModel.ProcessName = row[@"工序名称"].ToString();
                 //如果物料不为空，则应该有物料数量的。
                 if (!String.IsNullOrEmpty(bomHeaderModel.ChildItemNumber))
                 {
                     string numberString = row[@"数量"].ToString();
                     decimal number ;
                     if (decimal.TryParse(numberString,out number))
                     {
                         bomHeaderModel.Qty = number;
                     }
                     else
                     {
                         bomHeaderModel.Qty = 1;
                     }
                 }
                 bomHeaderModel.UseStatus = 1;
                 bomHeaderModel.FVersion = "1";
                 bomHeaderModel.ImportStatus = 1;
                 bomHeaderModel.ImportId = UserSession.CurrentUser.UserId;
                 bomHeaderModel.ImportDate = DateTime.Now;

                 //成品，半成品，等等
                 //bomHeaderModel.ParentType = ???

                 list.Add(bomHeaderModel);
             }
             try
             {
                 IBomHeaderPersist bomHeaderPersist = InstanceFactory.GetBomHeaderPersis();
                 bomHeaderPersist.SaveBomHeaders(list);
             }
             catch (Exception)
             {
                 throw;
             }
         }
    }
}
